package cn.lei.netty.herostory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * mysql 会话工厂
 * @author lei
 */
public  final class MySqlSessionFactory {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(MySqlSessionFactory.class);

    /**
     * MyBatis Sql 会话工厂
     */
    static private SqlSessionFactory sqlSessionFactory;

    /**
     * 初始化
     */
    public static void init(){
        try {
            //读取配置文件获取会话工厂
           sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(Resources.getResourceAsStream("MyBatisConfig.xml"));

           //测试数据库连接
            SqlSession tempSession = openSession();

            //获取连接对象并执行sql语句
            tempSession.getConnection().createStatement().execute("SELECT -1");

            //关闭临时会话
            tempSession.close();

            LOGGER.info("Mysql 数据库连接测试成功");
        }catch (Exception ex){
            LOGGER.error(ex.getMessage(),ex);
        }
    }

    /**
     * 创建mysql会话
     * @return
     */
    public static SqlSession openSession(){
        if (sqlSessionFactory == null) {
            throw new RuntimeException("sqlSessionFactory 尚未初始化");
        }
        return sqlSessionFactory.openSession(true);
    }
}
